#!/usr/bin/env python3
"""
配置管理模块
"""

import json
import logging
from pathlib import Path
from typing import Dict, List

logger = logging.getLogger(__name__)

class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_dir: Path):
        self.config_dir = config_dir
    
    def load_mirror_config(self, config_file: str) -> Dict[str, str]:
        """加载镜像配置"""
        config_path = self.config_dir / config_file
        
        if not config_path.exists():
            logger.error(f"配置文件不存在: {config_path}")
            return {}
        
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                if config_path.suffix == '.json':
                    config = json.load(f)
                else:
                    # 支持简单的 key=value 格式
                    config = {}
                    for line in f:
                        line = line.strip()
                        if line and not line.startswith('#'):
                            if '=' in line:
                                key, value = line.split('=', 1)
                                config[key.strip()] = value.strip()
            
            logger.info(f"加载配置: {config_path} ({len(config)} 条规则)")
            return config
            
        except Exception as e:
            logger.error(f"配置文件加载失败 {config_path}: {e}")
            return {}
    
    def save_mirror_config(self, config_file: str, config: Dict[str, str]) -> bool:
        """保存镜像配置"""
        config_path = self.config_dir / config_file
        
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                if config_path.suffix == '.json':
                    json.dump(config, f, indent=2, ensure_ascii=False)
                else:
                    for key, value in config.items():
                        f.write(f"{key}={value}\n")
            
            logger.info(f"配置已保存: {config_path}")
            return True
            
        except Exception as e:
            logger.error(f"配置文件保存失败 {config_path}: {e}")
            return False

